package com.db.priceApp.service;

import java.util.Random;
import java.util.logging.Logger;

import com.db.priceApp.domain.InstrumentList;
import com.db.priceApp.domain.Price;

public class PriceGenerator implements Runnable {

	private static final long TIME_STEP_FOR_PRICE_GENERATION = 10000;
	private static Logger logger = Logger.getLogger(PriceGenerator.class.getName());
	private InstrumentList instruments;

	public PriceGenerator(InstrumentList instruments) {
		this.instruments = instruments;
	}

	public static float generatePrice(int from, int to)
			throws IllegalArgumentException {
		float price;
		Random random = new Random();
		try {
			price = from + random.nextInt(to - from) + random.nextFloat();
		} catch (IllegalArgumentException e) {
			logger.warning("wrong range values for price generation");
			throw new IllegalArgumentException(e);
		}
		return price;
	}

	public static float generatePrice(String from, String to) {
		Random random = new Random();
		int fromInt = 0;
		int toInt = 0;
		float price = 0;
		try {
			fromInt = Integer.parseInt(from);
			toInt = Integer.parseInt(to);
			price = fromInt + random.nextInt(toInt - fromInt)
					+ random.nextFloat();
		} catch (NumberFormatException e) {
			logger.warning("wrong range values");
			throw new NumberFormatException("wrong range values");
		} catch (NullPointerException e) {
			logger.warning("there is no range values");
			throw new NullPointerException("there is no range values");
		} catch (IllegalArgumentException e) {
			logger.warning("wrong range values for price generation");
			throw new IllegalArgumentException(e);
		}
		return price;
	}

	@Override
	public void run() {
		Price price;

		while (true) {
			for (String instrName : instruments.getInstrumentList()) {
				price = instruments.getInstrumentPrice(instrName);
				instruments.changeInstrumentPrice(instrName,
						new Price(price.getRangeFrom(), price.getRangeTo()));
			}
			try {
				Thread.sleep(TIME_STEP_FOR_PRICE_GENERATION);
			} catch (InterruptedException e) {
				logger.warning("price generator was interrupted");
				continue;
			}
		}

	}

}
